//
// MongoDBC server test:
// 
// >curl "http://localhost:3002/set?k=name&v=Jani"
// "OK"
//
// >curl "http://localhost:3002/get?k=name"
// "Jani"
//

var JServer = require( '../jserver' );
var server = new JServer( {workers:1} );
server.ServerResponse.allowOrigin = '*';
if ( server.start() ) return;

console.log( "Connecting MongoDB" );
var MongoDBC = require( '../mongodbc' );
var db = new MongoDBC( {}, 'testDB', ['kv'], function(err,db) {
	if (err) 
		return console.error( "ERROR: MongoDB connection failed. "+err );
	console.log( "MongoDB connected" );
	
	server.get( "/set", function(req,res) {
		var o = {k:req.query.k, v:req.query.v};
		db.kv.insert( o, function(err,docs) {
			if (err) {console.error(err); return res.json(err);}
			console.dir(docs);
			res.json( "OK" );
		} );
	} );
	
	server.get( "/get", function(req,res) {
		var o = {k:req.query.k};
		db.kv.findOne( o, function(err,doc) {
			if (err) {console.error(err); return res.json(err);}
			res.json( doc.v );
		} );
	} );

	server.get( "/findAndModifyTest", function(req,res) {
		db.kv.remove( {k:'abc'}, function(err) {
			db.kv.findAndModify( {k:123}, [], {$set:{k:123}}, {upsert:true,'new':true}, function(err,doc) {
				if (err) return console.error( "ERROR: "+err );
				console.log( "findAndModify(new {k:123}):" ); console.dir( doc );

				db.kv.findAndModify( {_id:doc._id}, [], {$set:{k:124}}, {upsert:true,'new':true}, function(err,doc) {
					if (err) return console.error( "ERROR: "+err );
					console.log( "findAndModify(old -> {k:124}):" ); console.dir( doc );
					res.json( doc );
				} );
			} );
		} );
	} );

	server.get( "/findOneNotFound", function(req,res) {
		db.kv.findOne( {k:41231231}, function(err,doc) { // not found
			res.json( {err:err, doc:doc} );
		} );
	} );
	
} );

server.listenHTTP( 3002 );
